package com.guilin.system.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.guilin.common.core.domain.entity.SysUser;
import com.guilin.common.core.domain.model.LoginUser;
import com.guilin.common.enums.ApprovalStatus;
import com.guilin.common.enums.UserStatus;
import com.guilin.common.exception.ServiceException;
import com.guilin.common.utils.DateUtils;
import com.guilin.common.utils.SecurityUtils;
import com.guilin.common.utils.StringUtils;
import com.guilin.domain.Alumni;
import com.guilin.system.service.AlumniService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.guilin.mapper.AlumniVisitApplicationMapper;
import com.guilin.domain.AlumniVisitApplication;
import com.guilin.system.service.AlumniVisitApplicationService;

/**
 * 校友回访申请Service业务层处理
 * 
 * @author xiaoqi
 * @date 2025-06-23
 */
@Service
public class AlumniVisitApplicationServiceImpl implements AlumniVisitApplicationService
{
    @Autowired
    private AlumniVisitApplicationMapper alumniVisitApplicationMapper;

    @Autowired
    private AlumniService alumniService;

    /**
     * 查询校友回访申请
     * 
     * @param id 校友回访申请主键
     * @return 校友回访申请
     */
    @Override
    public AlumniVisitApplication selectAlumniVisitApplicationById(Long id)
    {
        return alumniVisitApplicationMapper.selectAlumniVisitApplicationById(id);
    }

    /**
     * 查询校友回访申请列表
     * 
     * @param alumniVisitApplication 校友回访申请
     * @return 校友回访申请
     */
    @Override
    public List<AlumniVisitApplication> selectAlumniVisitApplicationList(AlumniVisitApplication alumniVisitApplication)
    {
        return alumniVisitApplicationMapper.selectAlumniVisitApplicationList(alumniVisitApplication);
    }

    /**
     * 新增校友回访申请
     * 
     * @param alumniVisitApplication 校友回访申请
     * @return 结果
     */
    @Override
    public int insertAlumniVisitApplication(AlumniVisitApplication alumniVisitApplication)
    {

        // 业务校验
        validateApplication(alumniVisitApplication);


        // 设置申请基本信息
        alumniVisitApplication.setStatus(ApprovalStatus.PENDING.getCode()); // 待审核状态

        alumniVisitApplication.setCreateTime(DateUtils.getNowDate());

        return alumniVisitApplicationMapper.insertAlumniVisitApplication(alumniVisitApplication);
    }

    /**
     * 修改校友回访申请
     * 
     * @param alumniVisitApplication 校友回访申请
     * @return 结果
     */
    @Override
    public int updateAlumniVisitApplication(AlumniVisitApplication alumniVisitApplication)
    {
        // 获取原始记录
        AlumniVisitApplication existing = selectAlumniVisitApplicationById(alumniVisitApplication.getId());

        // 判断记录是否存在
        if (existing == null) {
            throw new ServiceException("申请记录不存在");
        }

        // 状态检查 已审核/已完成的记录不允许修改
        if((existing.getStatus() == ApprovalStatus.APPROVED.getCode() || existing.getStatus() == ApprovalStatus.COMPLETED.getCode())) {
            throw new ServiceException("已审核或已完成的记录不允许修改");
        }

        // 业务校验
        validateApplication(alumniVisitApplication);

        alumniVisitApplication.setUpdateTime(DateUtils.getNowDate());

        return alumniVisitApplicationMapper.updateAlumniVisitApplication(alumniVisitApplication);
    }

    /**
     * 批量删除校友回访申请
     * 
     * @param ids 需要删除的校友回访申请主键
     * @return 结果
     */
    @Override
    public int deleteAlumniVisitApplicationByIds(Long[] ids)
    {
        return alumniVisitApplicationMapper.deleteAlumniVisitApplicationByIds(ids);
    }

    /**
     * 删除校友回访申请信息
     * 
     * @param id 校友回访申请主键
     * @return 结果
     */
    @Override
    public int deleteAlumniVisitApplicationById(Long id)
    {
        return alumniVisitApplicationMapper.deleteAlumniVisitApplicationById(id);
    }


    /**
     * 审核校友回访申请
     * @param application
     * @return
     */
    public int reviewAlumniVisitApplication(AlumniVisitApplication application) {
        // 获取原始申请记录
        AlumniVisitApplication existing = selectAlumniVisitApplicationById(application.getId());
        // 检查记录是否存在
        if (existing == null) {
            throw new ServiceException("申请记录不存在");
        }
        // 检查记录是处于待审核
        if (existing.getStatus() != ApprovalStatus.PENDING.getCode()) {
            throw new ServiceException("只有处于待审状态的申请才能进行审核");
        }
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置审核人id
        application.setReviewerId(loginUser.getUserId());
        // 设置审核人姓名
        application.setReviewerName(loginUser.getUsername());
        // 设置审核时间
        application.setReviewTime(DateUtils.getNowDate());
        // 设置更新时间
        application.setUpdateTime(DateUtils.getNowDate());
        return alumniVisitApplicationMapper.updateAlumniVisitApplication(application);
    }


    /**
     * 查询个人的回访申请记录
     * @param alumniId
     * @return
     */
    public List<AlumniVisitApplication> selectPersonalApplications(Long alumniId) {

        return alumniVisitApplicationMapper.selectPersonalApplications(alumniId);
    }

    /**
     * 查询过期的回访申请记录
     * 过期条件：回访结束时间小于当前时间且状态为已通过
     * @param status 状态值
     * @param currentDate 当前日期
     * @return
     */
    public List<AlumniVisitApplication> selectExpiredApplications(Long status, Date currentDate) {
        return alumniVisitApplicationMapper.selectExpiredApplications(status, currentDate);
    }


    /**
     * 必填业务校验
     * @param app
     */
    private void validateApplication(AlumniVisitApplication app) {

        // 1. 校友ID不能为空
        if (app.getAlumniId() == null) {
            throw new ServiceException("校友ID不能为空");
        }

        // 2. 校验校友是否存在
        Alumni alumni = alumniService.selectAlumniById(app.getAlumniId());
        if (alumni == null) {
            throw new ServiceException("校友不存在,无法申请");
        }

        // 3. 校验校友状态是否有效
        if (alumni.getAccountStatus() == UserStatus.DISABLE.getCode()) {
            throw new ServiceException("校友账号已被停用，申请失败");
        }

        // 必填字段检查
        if (StringUtils.isAnyBlank(
                app.getApplicantName(),
                app.getContactPhone(),
                app.getVisitPurpose(),
                app.getVisitContent()
        )) {
            throw new ServiceException("必填字段不能为空");
        }

        // 时间有效性检查
        if (app.getVisitStartTime() != null &&
                app.getVisitEndTime() != null &&
                app.getVisitStartTime().after(app.getVisitEndTime())) {
            throw new ServiceException("回访开始时间不能晚于结束时间");
        }

        // 车辆信息检查
        if (app.getNeedVehicle() != null && app.getNeedVehicle() == 1) {
            if (StringUtils.isBlank(app.getVehicleInfo())) {
                throw new ServiceException("需要车辆入校时必须填写车辆信息");
            }
        }
    }
}
